package l1j.opqlo.Timer.Controler.Server;

import static l1j.server.server.model.skill.L1SkillId.狂暴打擊;
import static l1j.server.server.model.skill.L1SkillId.狩獵專長;
import static l1j.server.server.model.skill.L1SkillId.賞金獵人;
import static l1j.server.server.model.skill.L1SkillId.鋼鐵防禦;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.eric.StartCheckWarTime;
import l1j.opqlo.Server.L1World.L1World;
import l1j.opqlo.Server.L1World.WorldClan;
import l1j.opqlo.Server.L1World.WorldWar;
import l1j.server.Config;
import l1j.server.server.datatables.CastleTable;
import l1j.server.server.datatables.DoorSpawnTable;
import l1j.server.server.model.L1CastleLocation;
import l1j.server.server.model.L1Clan;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.L1War;
import l1j.server.server.model.L1WarSpawn;
import l1j.server.server.model.Instance.L1CrownInstance;
import l1j.server.server.model.Instance.L1DoorInstance;
import l1j.server.server.model.Instance.L1FieldObjectInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1TowerInstance;
import l1j.server.server.serverpackets.S_PacketBox;
import l1j.server.server.templates.L1Castle;

/**
 * 城戰計時軸
 *
 * @author dexc
 *
 */
public class ServerWarExecutor {

	private static final Logger _log = Logger.getLogger(ServerWarExecutor.class
			.getName());

	private static ServerWarExecutor _instance;

	public static ServerWarExecutor get() {
		if (_instance == null) {
			_instance = new ServerWarExecutor();
		}
		return _instance;
	}

	private final L1Castle[] _l1castle = new L1Castle[8];

	private final Calendar[] _war_start_time = new Calendar[8];

	private final Calendar[] _war_end_time = new Calendar[8];

	private final boolean[] _is_now_war = new boolean[8];

	private final String[] _castleName = new String[] { "肯特", "妖魔", "風木", "奇岩", "海音",
			"侏儒", "亞丁", "狄亞得要塞" };

	private ServerWarExecutor() {
		for (int i = 0; i < this._l1castle.length; i++) {
			this._l1castle[i] = CastleTable.getInstance().getCastleTable(i + 1);
			// TODO 修正攻城時間如果不是比現在時間久無法更新錯誤 by eric1300460
			final Calendar nowTime = this.getRealTime();
			final Calendar oldTime = this.getRealTime();
			oldTime.setTime(this._l1castle[i].getWarTime().getTime());
			this._war_start_time[i] = this._l1castle[i].getWarTime();
			oldTime.add(Config.ALT_WAR_TIME_UNIT, Config.ALT_WAR_TIME);

			if (StartCheckWarTime.getInstance().isActive(this._l1castle[i].getId())
					&& nowTime.after(oldTime)) {
				nowTime.add(Config.ALT_WAR_INTERVAL_UNIT,
						Config.ALT_WAR_INTERVAL);
				this._l1castle[i].setWarTime(nowTime);
				CastleTable.getInstance().updateCastle(this._l1castle[i]);
			}
			this._war_start_time[i] = this._l1castle[i].getWarTime();
			this._war_end_time[i] = oldTime;
			// TODO 修正攻城時間如果不是比現在時間久無法更新錯誤 by eric1300460
		}
	}

	/**
	 * 戰爭中城堡數量
	 *
	 * @return
	 */
	public int checkCastleWar() {
		int x = 0;
		for (int i = 0; i < 8; i++) {
			if (this._is_now_war[i]) {
				x++;
			}
		}
		return x;
	}

	/**
	 * 發布訊息給予上線玩家
	 *
	 * @param player
	 */
	public void checkCastleWar(final L1PcInstance player) {
		for (int i = 0; i < 8; i++) {
			if (this._is_now_war[i]) {
				// (641) %s的攻城戰正在進行中。
				player.sendPackets(new S_PacketBox(S_PacketBox.MSG_WAR_GOING,i + 1)); // %sの攻城戦が進行中です。
			}
		}
	}

	protected void checkWarTime() {
		try {
			for (int i = 0; i < 8; i++) {// i + 1 = 城堡編號
				final Calendar now = this.getRealTime();

				final int castleId = i + 1;
				if (this._war_start_time[i].before(now) // 戦争開始
						&& this._war_end_time[i].after(now)) {
					if (this._is_now_war[i] == false) {
						this._is_now_war[i] = true;

						// 召喚戰爭範圍旗幟
						final L1WarSpawn warspawn = new L1WarSpawn();
						warspawn.SpawnFlag(castleId);
						// 城門を修理して閉じる
						for (final L1DoorInstance door : DoorSpawnTable.getInstance().getDoorList()) {
							if (L1CastleLocation.checkInWarArea(castleId, door)) {
								door.repairGate();
							}
						}

						final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
						final String time = sdf.format(this._war_start_time[i].getTime());
						_log.info(this._castleName[i] + " 的攻城戰開始。時間: " + time);

						// (639) %s的攻城戰開始。
						L1World.getInstance().broadcastPacketToAll(new S_PacketBox(S_PacketBox.MSG_WAR_BEGIN,castleId));
						int[] loc = new int[3];
						for (final L1PcInstance pc : L1World.getInstance().getAllPlayers()) {
							if (L1CastleLocation.checkInWarArea(castleId, pc)&& !pc.isGm()) { // 戰爭範圍旗幟內
								final L1Clan clan = WorldClan.get().getClan(pc.getClanname());
								if (clan != null) {
									if (clan.getCastleId() == castleId) { // 城盟成員
										if (pc.hasSkillEffect(狂暴打擊)) {
											pc.removeSkillEffect(狂暴打擊);
										} else if (pc.hasSkillEffect(鋼鐵防禦)) {
											pc.removeSkillEffect(鋼鐵防禦);
										} else if (pc.hasSkillEffect(賞金獵人)) {
											pc.removeSkillEffect(賞金獵人);
										} else if (pc.hasSkillEffect(狩獵專長)) {
											pc.removeSkillEffect(狩獵專長);
										}
										continue;
									}
								}
								loc = L1CastleLocation.getGetBackLoc(castleId);
								L1Teleport.teleportByMagic(pc, loc[0], loc[1],(short) loc[2], 5, true);
							}
						}
					}
				} else if (this._war_end_time[i].before(now)) { // 攻城戰結束
					if (this._is_now_war[i] == true) {
						this._is_now_war[i] = false;
						// (640) %s的攻城戰結束。

						L1World.getInstance().broadcastPacketToAll(new S_PacketBox(S_PacketBox.MSG_WAR_END, i + 1)); // %sの攻城戦が終了しました。
						this._war_start_time[i].add(Config.ALT_WAR_INTERVAL_UNIT,Config.ALT_WAR_INTERVAL);
						this._war_end_time[i].add(Config.ALT_WAR_INTERVAL_UNIT,Config.ALT_WAR_INTERVAL);
						this._l1castle[i].setTaxRate(10); // 税率10%
						this._l1castle[i].setPublicMoney(0); // 公金クリア

						CastleTable.getInstance().updateCastle(this._l1castle[i]);


						final List<L1War> list = WorldWar.get().getWarList();
						for (final L1War war : list) {
							if (war.get_castleId() == castleId) {
								war.ceaseCastleWar();// 城堡戰爭時間終止,防禦方獲勝
							}
						}

						for (final L1Object l1object : L1World.getInstance().getObject()) {
							// 攻城戰旗幟消除
							if (l1object instanceof L1FieldObjectInstance) {
								final L1FieldObjectInstance flag = (L1FieldObjectInstance) l1object;
								if (L1CastleLocation.checkInWarArea(castleId,flag)) {
									flag.deleteMe();
								}
							}
							// 地面王冠物件刪除
							if (l1object instanceof L1CrownInstance) {
								final L1CrownInstance crown = (L1CrownInstance) l1object;
								if (L1CastleLocation.checkInWarArea(castleId,crown)) {
									crown.deleteMe();
								}
							}
							// 守護者之塔消除
							if (l1object instanceof L1TowerInstance) {
								final L1TowerInstance tower = (L1TowerInstance) l1object;
								if (L1CastleLocation.checkInWarArea(castleId,tower)) {
									tower.deleteMe();
								}
							}
						}
						// 重新召換守護者之塔
						final L1WarSpawn warspawn = new L1WarSpawn();
						warspawn.SpawnTower(castleId);

						// 城門を元に戻す
						for (final L1DoorInstance door : DoorSpawnTable
								.getInstance().getDoorList()) {
							if (L1CastleLocation.checkInWarArea(castleId, door)) {
								door.repairGate();
							}
						}

						// 戰爭結束訊息
//						L1World.getInstance().broadcastPacketToAll(new S_PacketBoxWar());

						final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
						final String time = sdf.format(now.getTime());
						_log.info(this._castleName[i] + " 的攻城戰結束。時間: " + time);
						
						/** 城堡技能檢查 */
						for (final L1Clan clan : WorldClan.get().getAllClans()) {
							if (clan.getCastleId() == this._l1castle[i].getId()) {
								this._l1castle[i].checkClanid(clan.getClanId());
								break;
							}
						}
						// 攻城獎勵
						// CastleWarGiftTable.get().get_gift(castle_id);
					}
				}
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
	}

	/**
	 * 目前時間
	 *
	 * @return
	 */
	public Calendar getRealTime() {
		final TimeZone _tz = TimeZone.getTimeZone(Config.TIME_ZONE);
		final Calendar cal = Calendar.getInstance(_tz);
		return cal;
	}

	public boolean isNowWar(final int castle_id) {
		return this._is_now_war[castle_id - 1];
	}

	public void setEndWarTime(final int castle_id, final Calendar calendar) {
		this._war_end_time[castle_id - 1] = (Calendar) calendar.clone();
		this._war_end_time[castle_id - 1].add(Config.ALT_WAR_TIME_UNIT,
				Config.ALT_WAR_TIME);
		// _war_end_time[castle_id - 1] = calendar;
	}

	public void setWarTime(final int castle_id, final Calendar calendar) {
		this._war_start_time[castle_id - 1] = (Calendar) calendar.clone();
	}
}
